package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.service.UserService;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import com.example.onlinemusic.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 用户登录
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(@RequestParam String username, @RequestParam String password,
                                           HttpServletRequest request) {
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);
        // 直接调用mapper层
        User userInfo = userMapper.selectByName(username);
        if (userInfo == null) {
            return new ResponseBodyMessage<>(-1, "没有此用户!", userInfo);
        } else {
            // 检查密码是否正确
            boolean matches = bCryptPasswordEncoder.matches(password, userInfo.getPassword());
            if (!matches) {
                return new ResponseBodyMessage<>(-1, "密码错误！", null);
            }
            // 在当前会话（session）中添加属性，来存放当前用户的信息
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY, userInfo);
            return new ResponseBodyMessage<>(0, "登录成功", userInfo);
        }
    }


    /**
     * 用户注册
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/register")
    public ResponseBodyMessage<User> register(@RequestParam String username, @RequestParam String password) {

        User find = userMapper.selectByName(username);
        if (find != null) {
            return new ResponseBodyMessage<>(-1, "用户已存在！", null);
        } else {
            User registerUser = new User();
            registerUser.setUsername(username);
            registerUser.setPassword(password);
            int result = userService.register(registerUser);// service层处理加密业务
            if (result > 0) {
                return new ResponseBodyMessage<>(0, "注册成功！", registerUser);
            } else {
                return new ResponseBodyMessage<>(-1, "注册失败，请联系管理员！", null);
            }
        }

    }
}
